package com.ld.shieldsb.thirdauth.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xkcoding.justauth.AuthRequestFactory;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;

@Slf4j
@RestController
@RequestMapping("/ssboauth")
@RequiredArgsConstructor(onConstructor = @__({ @Autowired })) // 为所有final或者@NOTNULL的字段增加避免重复写@Autowired，如factory
public class OauthTestController {
    private final AuthRequestFactory factory;

    @GetMapping
    public List<String> list() {
        return factory.oauthList();
    }

    /**
     * 登录类型
     */
    @GetMapping("/list")
    public Map<String, Object> loginType() {
        List<String> oauthList = factory.oauthList();
        Map<String, Object> obj = oauthList.stream().collect(Collectors.toMap(oauth -> oauth.toLowerCase() + "登录",
                oauth -> "http://work.11315.cn:28800/ssboauth/login/" + oauth.toLowerCase()));
        return obj;
    }

    /**
     * 登录
     *
     * @param oauthType
     *            第三方登录类型
     * @param response
     *            response
     * @throws IOException
     */
    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 登录成功后的回调
     *
     * @param oauthType
     *            第三方登录类型
     * @param callback
     *            携带返回的信息
     * @return 登录成功后的信息
     */
    @RequestMapping("/{type}/callback")
    public AuthResponse callback(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        AuthResponse response = authRequest.login(callback);
        log.info("【response】= {}", JSONUtil.toJsonStr(response));
        return response;
    }

}